package com.wzs.setting.service.impl;

import com.wzs.exception.LoginException;
import com.wzs.setting.dao.AuthorMapper;
import com.wzs.setting.domain.Author;
import com.wzs.setting.domain.Readr;
import com.wzs.setting.service.AuthorService;
import com.wzs.utils.MD5Util;
import com.wzs.utils.UUIDUtil;
import com.wzs.vo.PaginationVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AuthorServiceImpl implements AuthorService {

    @Resource
    private AuthorMapper authorMapper;

    @Override
    public PaginationVO<Readr> pageList(HashMap<String, Object> map) {
        //取得total
        int total = authorMapper.getTotalByCondition(map);
        //取得list
        List<Readr> dataList = authorMapper.getReaderListByCondition(map);
        //创建一个vo对象,将total和datalist封装到vo中
        PaginationVO<Readr> vo = new PaginationVO<>();
        vo.setTotal(total);
        vo.setDataList(dataList);

        //将vo返回
        return vo;
    }

    @Override
    public Readr getReaderList(String id) {
        //取List<Readr>
        return authorMapper.getReaderList(id);
    }

    @Override
    public boolean delete(String[] ids) {
        boolean flag = true;

        //删除读者信息
        int count3 = authorMapper.delete(ids);
        if (count3 != ids.length) {
            flag = false;
        }
        return flag;
    }

    @Override
    public boolean register(Author author) {

        boolean flag = true;
        String id = UUIDUtil.getUUID();
        String password = MD5Util.getMD5(author.getPassword());
        author.setId(id);
        author.setPassword(password);

        int count = authorMapper.register(author);

        if (count != 1) {
            flag = false;
        }

        return flag;
    }


    @Override
    public Author login(String username, String password) throws LoginException {
        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        Author author = authorMapper.login(map);
        if (author == null) {
            throw new LoginException("账号或密码错误");
        }
        return author;


    }
}
